<script setup lang="ts">
import { ElTabs, ElTabPane, type TabPaneName, ElInput, ElButton } from 'element-plus';
import { ref, computed, watch } from 'vue';

defineOptions({
  name: 'WorkBrowser',
});
const emits = defineEmits(['change']);

// 书签
const bookmarks = ref<Array<{title: string, url: string}>>([])
const showBookmarks = ref(false)

// 加载书签
const loadBookmarks = () => {
  const saved = localStorage.getItem('browser-bookmarks')
  if (saved) {
    try {
      bookmarks.value = JSON.parse(saved)
    } catch {
      bookmarks.value = []
    }
  }
}

// 保存书签
const saveBookmarks = () => {
  localStorage.setItem('browser-bookmarks', JSON.stringify(bookmarks.value))
}

// 初始化时加载书签
loadBookmarks()

// 监听书签变化
watch(bookmarks, () => {
  saveBookmarks()
}, { deep: true })

// 检查当前页面是否已收藏
const isBookmarked = computed(() => {
  return currentTab.value ? 
         bookmarks.value.some(b => b.url === currentTab.value?.url) : 
         false
})

// 添加/删除书签
const toggleBookmark = () => {
  if (currentTab.value) {
    const { title, url } = currentTab.value
    if (isBookmarked.value) {
      removeBookmark(url)
    } else {
      addBookmark(title, url)
    }
  }
}

// 添加书签
const addBookmark = (title: string, url: string) => {
  if (!bookmarks.value.some(b => b.url === url)) {
    bookmarks.value.push({ title, url })
  }
}

// 删除书签
const removeBookmark = (url: string) => {
  bookmarks.value = bookmarks.value.filter(b => b.url !== url)
}

// 打开书签
const openBookmark = (url: string) => {
  navigate(url)
  showBookmarks.value = false
}

// 当前标签页
let tabIndex = 2
const editableTabsValue = ref('1')
const editableTabs = ref([
  {
    title: 'Tab 1',
    name: '1',
    url: 'https://www.baidu.com',
    history: [],
    historyIndex: -1
  },
  {
    title: 'Tab 2',
    name: '2',
    url: 'https://cn.bing.com/',
    history: [],
    historyIndex: -1
  },
])

interface Tab {
  title: string
  name: string
  url: string
  history: string[]
  historyIndex: number
}

// 当前标签页数据
const currentTab = computed<Tab | undefined>(() => {
  return editableTabs.value.find(tab => tab.name === editableTabsValue.value)
})

// 地址栏输入
const address = ref('')

// 导航控制
const canGoBack = computed<boolean>(() => {
  return currentTab.value ? currentTab.value.historyIndex > 0 : false
})

const canGoForward = computed<boolean>(() => {
  return currentTab.value ? 
         currentTab.value.historyIndex < currentTab.value.history.length - 1 : 
         false
})

const goBack = () => {
  if (canGoBack.value && currentTab.value) {
    const tab = currentTab.value
    tab.historyIndex--
    tab.url = tab.history[tab.historyIndex]
  }
}

const goForward = () => {
  if (canGoForward.value && currentTab.value) {
    const tab = currentTab.value
    tab.historyIndex++
    tab.url = tab.history[tab.historyIndex]
  }
}

const refresh = () => {
  if (currentTab.value) {
    const tab = currentTab.value
    tab.url = tab.history[tab.historyIndex]
  }
}

const navigate = (url: string) => {
  if (!currentTab.value) return
  
  const tab = currentTab.value
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://' + url
  }
  
  // 添加到历史记录
  tab.history = tab.history.slice(0, tab.historyIndex + 1)
  tab.history.push(url)
  tab.historyIndex++
  tab.url = url
  tab.title = '加载中...'
}

// 更新标签页标题
const updateTabTitle = (tab: Tab, iframe: HTMLIFrameElement) => {
  try {
    // 尝试获取iframe的标题
    const title = iframe.contentDocument?.title || tab.url
    tab.title = title
  } catch (error) {
    // 跨域限制时使用URL作为标题
    tab.title = new URL(tab.url).hostname
  }
}

const addTab = (targetName: string) => {
  const newTabName = `${++tabIndex}`
  editableTabs.value.push({
    title: targetName||'New Tab',
    name: newTabName,
    url: 'about:blank',
    history: [],
    historyIndex: -1
  })
  editableTabsValue.value = newTabName
}
const removeTab = (targetName: TabPaneName) => {
  const tabs = editableTabs.value
  let activeName = editableTabsValue.value
  if (activeName === targetName) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetName) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeName = nextTab.name
        }
      }
    })
  }

  editableTabsValue.value = activeName
  editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
}
const changeTab = (target: TabPaneName) => {
  const targetTab = editableTabs.value.find((tab) => tab.name === target);
  address.value = targetTab?.url || '';
  console.log(address.value)
  emits('change', {url:address.value})
}
const loadUrl = (url: string) => {
  // 确保 URL 以 http:// 或 https:// 开头
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://' + url;
  }
  return url;
}

defineExpose({
  addTab,
  navigate
})
</script>

<template>
  <div class="wos-browser">
    <div class="hidden toolbar">
      <ElButton @click="toggleBookmark" text>
        <span :class="isBookmarked ? 'icon-[mdi--bookmark]' : 'icon-[mdi--bookmark-outline]'"></span>
      </ElButton>
      <ElButton @click="showBookmarks = !showBookmarks" text>
        <span class="icon-[mdi--star]"></span>
      </ElButton>
      <div class="navigation">
        <ElButton :disabled="!canGoBack" @click="goBack" text>
          <span class="icon-[mdi--arrow-left]"></span>
        </ElButton>
        <ElButton :disabled="!canGoForward" @click="goForward" text>
          <span class="icon-[mdi--arrow-right]"></span>
        </ElButton>
        <ElButton @click="refresh" text>
          <span class="icon-[mdi--refresh]"></span>
        </ElButton>
      </div>
      <ElInput
        v-model="address"
        placeholder="输入网址或搜索内容"
        @keyup.enter="navigate(address)"
      />
    </div>
    <div class="main">
      <ElTabs 
        v-model="editableTabsValue" 
        type="border-card" 
        closable 
        @tab-remove="removeTab"
        @tab-change="changeTab"
      >
        <ElTabPane class="w-full h-full" v-for="item in editableTabs" :key="item.name" :label="item.title"
          :name="item.name">
          <iframe 
            width="100%" 
            height="100%" 
            :src="loadUrl(item.url)"
            @load="(e) => updateTabTitle(item, e.target as HTMLIFrameElement)"
          ></iframe>
          
        </ElTabPane>
      </ElTabs>
    </div>

    <!-- 书签面板 -->
    <ElDrawer v-model="showBookmarks" title="书签" size="25%">
      <div class="bookmark-list">
        <div 
          v-for="bookmark in bookmarks" 
          :key="bookmark.url"
          class="bookmark-item"
          @click="openBookmark(bookmark.url)"
        >
          <i class="ri-bookmark-fill"></i>
          <span class="title">{{ bookmark.title }}</span>
          <span class="url">{{ bookmark.url }}</span>
          <ElButton 
            type="danger" 
            size="small" 
            @click.stop="removeBookmark(bookmark.url)"
          >
            <i class="ri-delete-bin-line"></i>
          </ElButton>
        </div>
      </div>
    </ElDrawer>
  </div>
</template>

<style lang="scss" scoped>
.bookmark-list {
  padding: 10px;
  
  .bookmark-item {
    display: flex;
    align-items: center;
    padding: 8px;
    margin-bottom: 8px;
    border-radius: 4px;
    cursor: pointer;
    transition: background-color 0.2s;

    &:hover {
      background-color: var(--el-fill-color-light);
    }

    i {
      margin-right: 8px;
      color: var(--el-color-primary);
    }

    .title {
      flex: 1;
      margin-right: 8px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .url {
      flex: 2;
      color: var(--el-text-color-secondary);
      font-size: 0.9em;
      margin-right: 8px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
</style>

<style lang="scss">
@import url('./css/browser.scss');
</style>
